/**
 * Copyright 2004 Cordys R&D B.V. 
 * 
 * This file is part of the Cordys FTP Connector. 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 package com.eibus.applicationconnector.ftp;

import com.eibus.xml.nom.Node;
import com.eibus.xml.xpath.XPath;
import com.eibus.soap.fault.Fault;
import com.eibus.applicationconnector.ftp.localization.message.Messages;

/**
 * This class is the handler for FTP's DIR command
 */
class ListDirectories extends FTPCommand
{
	private int responseNode;	

    @Override
	public boolean prepare()
	{
		responseNode = response.getXMLNode();
		
		addRequestDetailsToResponse(requestXML, responseNode);
		
		int directoryNode = Node.getElementNS(requestXML, "directory", getNameSpace());
		if(directoryNode==0)
		{
            Fault fault = response.createSOAPFault(Fault.Codes.CLIENT, Messages.DIRECTORY_NOT_SPECIFIED);
            addFaultDetails2(fault.getDetail(), null, DEFAULT_QNAME, null, null);
            return false;
        }

		Node.appendToChildren(directoryNode, responseNode);
		
        int[] pathNodes = XPath.getMatchingNodes("path", null, directoryNode);
        if(pathNodes.length ==0 )
		{
            Fault fault = response.createSOAPFault(Fault.Codes.CLIENT,Messages.DIRECTORY_NOT_SPECIFIED);
            addFaultDetails2(fault.getDetail(),null,DEFAULT_QNAME,null,null);
            return false;
        }

        Node.appendToChildren(Node.clone(Node.getElementNS(requestXML, "directory", getNameSpace()), true), responseNode);

        for (int index = 0; index < pathNodes.length; index ++)
        {
    		int listOfFilesNode;
			try
			{
				/* Invoke the DIR command on the adapter */
				listOfFilesNode = adapter.listDirectories(pathNodes[index]);
			}
			catch (FTPException e)
			{
	            Fault fault = response.createSOAPFault(Fault.Codes.CLIENT, Messages.SPECIFIED_FILE_NOT_FOUND_WITH_PARAMETER, new String[]{e.getDetailedMessage()});
	            addFaultDetails2(fault.getDetail(),e,DEFAULT_QNAME,null,null);
	            return false;
			}
    		Node.appendToChildren(listOfFilesNode, pathNodes[index]);
        }
		
		return true;
	}
    
    @Override
	public void commit()
	{	
    	/* After the command is complete, disconnect the adapter from the FTP server */
    	adapter.disconnect();
	}
}